package logic

import (
	"context"
	"fmt"
	"math/rand"
	"strconv"
	"teacher1/model/redis"
	"teacher1/pkg"
	"time"

	"teacher1/teacherrpc/internal/svc"
	"teacher1/teacherrpc/teacherrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type SendSmsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSendSmsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendSmsLogic {
	return &SendSmsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SendSmsLogic) SendSms(in *teacherrpc.SendSmsRequest) (*teacherrpc.SendSmsResponse, error) {
	// todo: add your logic here and delete this line
	//获取图形验证码
	get := redis.Rdb.Get("captchasendSms" + in.Mobile)
	if get.Val() != in.CaptChaCode {
		return nil, fmt.Errorf("图形验证码错误，请重新输入")
	}
	cmd := redis.Rdb.Get("sendSmsNumber" + in.Mobile)
	if cmd.Val() != "" {
		return nil, fmt.Errorf("当前短信限制5分钟内只能发送一次,请过后再来")
	}
	//进行短信发送
	rands := rand.Intn(9000) + 1000
	resp, err := pkg.SendSms(in.Mobile, strconv.Itoa(rands))
	if err != nil {
		return nil, err
	}
	if *resp.Body.Code != "OK" {
		return nil, fmt.Errorf(*resp.Body.Message)
	}
	redis.Rdb.Set("sendSms"+in.Source+in.Mobile, rands, time.Minute*5)
	//设置5分钟限制
	redis.Rdb.Set("sendSmsNumber"+in.Mobile, "123123", time.Minute*5)
	return &teacherrpc.SendSmsResponse{}, nil
}
